/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.doc.sender.ui;

import com.database.entity.DocumentEnclose;
import com.database.entity.DocumentSources;
import com.database.entity.Documents;
import com.database.entity.PdfFiles;
import database.senderUtil;
import java.io.File;
import java.io.FileInputStream;
import java.lang.InstantiationException;
import java.net.InetAddress;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import org.hibernate.*;

/**
 *
 * @author parent
 */
public class DocInfoFrame extends javax.swing.JFrame {
    private DocumentSources docsource;
    private Documents dokumen;
    /**
     * Creates new form sendToFrame
     */
    public DocInfoFrame() {
        initComponents();
        populateDocomentSource();
        populateList();
    }
    FileFilter pdfFilter = new FileFilter() {

        public boolean accept(File f) {
            return f.isDirectory() || f.getName().endsWith(".pdf");
        }

        public String getDescription() {
            return "Choose a PDF file";
        }
    };
    private File prevDirChoice;
    
    public void sendToDatabase(File f) {
        
        Session session = senderUtil.getSessionFactory().openSession();
        Transaction transaction = null;
         
                
        try {
            transaction = session.beginTransaction();
            FileInputStream fis=new FileInputStream(f);
            InetAddress ownIP=InetAddress.getLocalHost();
            PDFViewerFrame pview=new PDFViewerFrame(false);
            byte[] ByteBuffer=pview.readAndClose(fis);
            pview.setVisible(false);
            if (!pview.isFileInDatabase(f.getName())){
                
                com.database.entity.PdfFiles pf=new com.database.entity.PdfFiles();
                pf.setFileName(f.getName());
                pf.setFileContent(Hibernate.createBlob(ByteBuffer));
                pf.setIpAddress(ownIP.getHostAddress());
                pf.setStatus(0);
                pf.setDateCreated(new Date());
                session.save(pf);
                transaction.commit();
                new JOptionPane().showMessageDialog(this,"File berhasil disimpan");
               
            } else {
               new JOptionPane().showMessageDialog(this,"File sudah ada atau tersimpan di database"); 
            }
 
            pview.dispose();
            System.out.println("Records inserted sucessessfully");
        } 
        catch (Exception e){
            new JOptionPane().showMessageDialog(this,"File "+
                     f.getName()+" tidak Ada!"); 
        }
        finally {
            session.close();
        }
        
         
    }
    
    private void doOpenFile() {
        try {
            JFileChooser fc = new JFileChooser();
            fc.setCurrentDirectory(prevDirChoice);
            fc.setFileFilter(pdfFilter);
            fc.setMultiSelectionEnabled(false);
            int returnVal = fc.showOpenDialog(this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
               
                prevDirChoice = fc.getSelectedFile();
                sendToDatabase(prevDirChoice);    
                populateList();
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this,
                    "Opening files from your local " +
                    "disk is not available\nfrom the " +
                    "Java Web Start version of this " +
                    "program.\n",
                    "Error opening directory",
                    JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        }
    }
    public void populateList(){
        Session session = senderUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            String queryString = "from PdfFiles order by file_name";
            Query query = session.createQuery(queryString);
            List listRecord=query.list();
            DefaultListModel model=new DefaultListModel();
            if (listRecord!=null){
               for (Object o:listRecord){
                   PdfFiles pdf=(PdfFiles)o;
                   model.addElement(new Item(pdf.getId(),pdf.getFileName()));
                   //System.out.println("check : "+pdf.getFileName());
               }    
            }
            attachList.setModel(model);
            transaction.commit();
            
            
        } catch (Exception e){
            //return false;
            System.out.println("Error : "+e.getMessage());
        }  
}
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        cbDocSource = new javax.swing.JComboBox();
        btnAdd = new javax.swing.JButton();
        Alamat = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        TanggalTerima = new javax.swing.JFormattedTextField();
        jLabel6 = new javax.swing.JLabel();
        TanggalSurat = new javax.swing.JFormattedTextField();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        btnSend = new javax.swing.JButton();
        NoSurat = new javax.swing.JTextField();
        NoAgenda = new javax.swing.JTextField();
        JumlahLampiran = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        Judul = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();
        NoDokumen = new javax.swing.JTextField();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        attachList = new javax.swing.JList();
        btnEnclose = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Dokumen Asal"));

        jLabel1.setText("Dari :");

        cbDocSource.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                cbDocSourceFocusLost(evt);
            }
        });

        btnAdd.setText("New");
        btnAdd.setToolTipText("Masukkan Asal Dokumen bila Belum Ada");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        Alamat.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        Alamat.setText("Alamat");
        Alamat.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        Alamat.setFocusable(false);
        Alamat.setPreferredSize(new java.awt.Dimension(200, 14));
        Alamat.setRequestFocusEnabled(false);

        jButton1.setText("Add Attachment");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cbDocSource, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Alamat, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButton1)
                    .addComponent(btnAdd))
                .addContainerGap(139, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(cbDocSource, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAdd))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(Alamat, javax.swing.GroupLayout.DEFAULT_SIZE, 55, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addGap(0, 32, Short.MAX_VALUE))))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Informasi Surat"));

        jLabel5.setText("Diterima Tanggal :");

        TanggalTerima.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat("dd/MM/yyyy"))));

        jLabel6.setText("Tanggal Surat :");

        TanggalSurat.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat("dd/MM/yyyy"))));

        jLabel7.setText("No. Surat :");

        jLabel8.setText("No. Agenda :");

        jLabel9.setText("Jumlah Lampiran :");

        btnSend.setText("Kirim");
        btnSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSendActionPerformed(evt);
            }
        });

        jLabel10.setText("Judul :");

        jLabel11.setText("No. Dokumen :");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(jPanel2Layout.createSequentialGroup()
                            .addContainerGap()
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel5)
                                .addComponent(jLabel9))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGroup(jPanel2Layout.createSequentialGroup()
                            .addGap(33, 33, 33)
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jLabel7)
                                .addComponent(jLabel8))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel10)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel11)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(TanggalTerima, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(TanggalSurat, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnSend))
                    .addComponent(NoSurat, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(NoAgenda, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(JumlahLampiran, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Judul)
                    .addComponent(NoDokumen))
                .addGap(56, 56, 56))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(TanggalTerima, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(TanggalSurat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnSend))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(NoSurat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(NoAgenda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(JumlahLampiran, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Judul, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(NoDokumen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel11))
                .addContainerGap(60, Short.MAX_VALUE))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Attachment List"));

        jScrollPane2.setViewportView(attachList);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 362, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 95, Short.MAX_VALUE)
        );

        btnEnclose.setText("Enclose");
        btnEnclose.setToolTipText("Lampirkan");
        btnEnclose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEncloseActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnEnclose)
                .addContainerGap(98, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(19, 19, 19)
                        .addComponent(btnEnclose)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        java.awt.Dimension dialogSize = getSize();
        setLocation((screenSize.width-dialogSize.width)/2,(screenSize.height-dialogSize.height)/2);
    }// </editor-fold>//GEN-END:initComponents
    private DocumentSources getDocumentSourceRecords(int id){
        Session session = senderUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            String queryString = "from DocumentSources where id=:id";
            Query query = session.createQuery(queryString);
            query.setInteger("id", id);
            DocumentSources sources=(DocumentSources)query.uniqueResult();
          
            transaction.commit();
            session.close();
            if(sources!=null){
                // System.out.println("File sudah ada");
                return sources;
               
            } else return null;
            
        } catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
    private void cbDocSourceFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_cbDocSourceFocusLost
        // TODO add your handling code here:
        if (evt.getSource()!=null){
        JComboBox cb=(JComboBox)evt.getSource();
        Item item=(Item)cb.getSelectedItem();
        docsource=getDocumentSourceRecords(item.getId());
        Alamat.setText("<html>"+docsource.getAddress()+" "+docsource.getCity()+" " 
                +docsource.getPostalCode()+"\r\n"+
                "Telp. "+docsource.getTelp()+" Fax. "+docsource.getFax()+"</html>");
        }
    }//GEN-LAST:event_cbDocSourceFocusLost
    
    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        // TODO add your handling code here:
        DocSourceFrame sourceFrame=new DocSourceFrame();
        sourceFrame.setVisible(true);
    }//GEN-LAST:event_btnAddActionPerformed

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        // TODO add your handling code here:
        populateDocomentSource();
    }//GEN-LAST:event_formWindowActivated

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        doOpenFile();
    }//GEN-LAST:event_jButton1ActionPerformed
    public void InsertDocuments(Documents dokumen){
        Session session = senderUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            session.save(dokumen);
            transaction.commit();
            session.close();    
            
        } catch (Exception e){
            //return false;
            System.out.println(e.getMessage());
        }  
    }
    private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSendActionPerformed
        // TODO add your handling code here:
        try {
            DateFormat formatter ;
            Date tglSurat;
            Date tglTerima;
            formatter = new SimpleDateFormat("dd/MM/yyyy");
            tglSurat = (Date)formatter.parse(TanggalSurat.getText());  
            tglTerima= (Date)formatter.parse(TanggalTerima.getText());
            Calendar sekarang=Calendar.getInstance();
            
            dokumen=new Documents();
            dokumen.setAgendaNo(NoAgenda.getText());
            dokumen.setLetterSubject(Judul.getText());
            dokumen.setAttachmentCount(Integer.parseInt(JumlahLampiran.getText()));
            dokumen.setDocumentDate(tglSurat);
            dokumen.setDateAccept(tglTerima);
            dokumen.setDocumentSources(docsource);
            dokumen.setDocumentNo(NoDokumen.getText());
            dokumen.setLetterDisposition("");
            dokumen.setDateCreated(sekarang.getTime());
            dokumen.setLastRevised(sekarang.getTime());
            dokumen.setLastStatus(0);
            dokumen.setSignOff1(0);
            dokumen.setSignOff2(0);
            dokumen.setDocumentVersion(0);
            dokumen.setNextRecipient(2);
            dokumen.setReviews(0);
            InsertDocuments(dokumen);
        } catch (Exception e){
            
        }
        
    }//GEN-LAST:event_btnSendActionPerformed
    private void EnclosedAttachment(){
        Session session = senderUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
        for (Object o:attachList.getSelectedValuesList()){
            Item item=(Item)o;
            //System.out.println(Integer.toString(item.getId())+":"+item.getDescription());
            DocumentEnclose encloses=new DocumentEnclose();
            PdfFiles files=getFiles(item.getId());
            encloses.setPdfFiles(files);
            encloses.setDocuments(dokumen);
            session.save(encloses);
        }
          transaction.commit();
          new JOptionPane().showMessageDialog(this,
                  "Dokumen berhasil di tambahkan ke database!");
        } catch (Exception e){
            
        }
    }
    private void btnEncloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEncloseActionPerformed
        // TODO add your handling code here:
        if (dokumen!=null&&attachList.getSelectedValuesList()!=null){
            EnclosedAttachment();
            new JOptionPane().showMessageDialog(this,
                    "Lampiran berhasil di tambahkan ke dokumen!");
        } else {
            new JOptionPane().showMessageDialog(this,"Anda belum memilih file atau dokumen belum tersimpan!");
        }
    }//GEN-LAST:event_btnEncloseActionPerformed
    public PdfFiles getFiles(int id){
        Session session = senderUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            String queryString = "from PdfFiles where id=:id";
            Query query = session.createQuery(queryString);
            query.setInteger("id", id);
            PdfFiles pdfs=(PdfFiles)query.uniqueResult();
            transaction.commit();
            if(pdfs!=null){
                // System.out.println("File sudah ada");
                return pdfs;
               
            } else return null;
            
        } catch (Exception e){
//            e.printStackTrace();
            return null;
        }
    }
    private void populateDocomentSource(){
        Session session = senderUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
                cbDocSource.removeAllItems();
                String queryString= "from DocumentSources order by source_name asc";
                Query query = session.createQuery(queryString);
                List listRecord=query.list();
                if (listRecord!=null){
                    for (Object o:listRecord){
                        DocumentSources ds=(DocumentSources)o;  
                        cbDocSource.addItem(new Item(ds.getId(),ds.getSourceName()));
                    }
                  
                }
               
             
          
            transaction.commit();
            session.close();
            
        } catch (Exception e){
            //return false;
//            e.printStackTrace();
        }  
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(DocInfoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(DocInfoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(DocInfoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DocInfoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new DocInfoFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel Alamat;
    private javax.swing.JTextField Judul;
    private javax.swing.JTextField JumlahLampiran;
    private javax.swing.JTextField NoAgenda;
    private javax.swing.JTextField NoDokumen;
    private javax.swing.JTextField NoSurat;
    private javax.swing.JFormattedTextField TanggalSurat;
    private javax.swing.JFormattedTextField TanggalTerima;
    private javax.swing.JList attachList;
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnEnclose;
    private javax.swing.JButton btnSend;
    private javax.swing.JComboBox cbDocSource;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration//GEN-END:variables
}
